<template>
  <div id="goodsList">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline" >
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="商品名称">
                <a-input v-model="queryParam.name" placeholder="请输入商品名称"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="商品分类">
                <a-select
                  placeholder="请选择商品分类"
                  v-model="queryParam.category"
                >
                  <a-select-option
                    v-for="item in categoryOptions"
                    :key="item.id"
                    :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="上架状态">
                <a-select
                  placeholder="请选择上架状态"
                  @change="statusChange"
                  :value="queryParam.upper_shelf_state"
                >
                  <a-select-option
                    v-for="item in StatusOptions"
                    :key="item.id"
                    :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md=" 6 || 24" :sm="24">
              <a-button type="primary" @click="queryTable">查询</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-table :columns="columns" :dataSource="dataList" :pagination="false" rowKey="id">
        <a slot="name" slot-scope="text" href="javascript:;">{{ text }}</a>
        <span slot="tags" slot-scope="tags">
          <a-tag v-for="tag in tags" color="blue" :key="tag">{{ tag }}</a-tag>
        </span>
        <div slot="state" slot-scope="text" >
          <a-tag color="blue">{{ text | statusFilter }}</a-tag>
        </div>
        <div slot="hot" slot-scope="text" >
          <a-tag color="blue">{{ text | statusFilter }}</a-tag>
        </div>
        <span slot="action" slot-scope="record">
          <a-dropdown>
            <a class="ant-dropdown-link">
              <a-icon type="ordered-list"></a-icon>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a href="javascript:;" @click.prevent="editHotShelves(record)">爆款编辑</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:" @click.prevent="editGood(record)">编辑</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm
                  v-if="dataList.length"
                  title="确认删除?"
                  @confirm="() => onDelete(record.id)">
                  <a href="javascript:">删除</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:" @click.prevent="changeShelves(record)">上架</a>
              </a-menu-item>
              <a-menu-item>
                <a href="javascript:" @click.prevent="changeHotShelves(record)">爆款上架</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
      <my-pagination
        :total="pagination.totalCount"
        :pageSize="pagination.pageSize"
        :current="pagination.pageNo"
        @onChange="onChangePage"
        @onShowSizeChange="onShowSizeChangePage"
      ></my-pagination>
    </a-card>
    <!--爆款编辑弹框-->
    <a-modal
      title="爆款商品编辑"
      :visible="visible"
      @ok="saveCategory"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
    >
      <div>
        <a-form :form="dialogModel">
          <a-form-item
            label="图片上传"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <div class="clearfix">
              <a-upload
                :fileList="fileList"
                :remove="handleRemove"
                :beforeUpload="beforeUpload"
                @change="handleUpload"
              >
                <a-button v-if="fileList.length < 1">
                  <a-icon type="upload" ></a-icon> 选择图片
                </a-button>
              </a-upload>
              <div class="banner_img" style="display: flex; " v-if="imgUrl">
                <img :src="'https://admin.muyumall.com'+imgUrl" alt="" height="80px">
                <div style="cursor: pointer" @click="delImg"><a-icon type="delete" ></a-icon>
                </div>
              </div>
            </div>
          </a-form-item>
          <a-form-item
            label="序号"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <a-input
              v-decorator="[
                'recommend_serial_no',
                {rules: [{ required: true, message: '请输入序号!!' }]}
              ]"
              placeholder="请输入序号..."
            ></a-input>
          </a-form-item>
          <a-form-item
            label="推广文案"
            :label-col="{ span: 5 ,offset: 4}"
            :wrapper-col="{ span: 10 }"
          >
            <a-input
              v-decorator="['slogan',]"
              placeholder="请输入推广文案..."
            ></a-input>
          </a-form-item>
        </a-form>

      </div>
    </a-modal>
    <!--商品分类上下架-->
    <a-modal
      title="商品分类上下架"
      v-model="shelfVisible"
      @ok="changeState"
      okText="确认"
      cancelText="取消"
    >
      <a-radio-group v-model="upper_shelf_state">
        <a-radio :value="1">上架</a-radio>
        <a-radio :value="2">下架</a-radio>
      </a-radio-group>
    </a-modal>
    <!--爆款商品分类上下架-->
    <a-modal
      title="爆款商品分类上下架"
      v-model="shelfHotVisible"
      @ok="changeHotState"
      okText="确认"
      cancelText="取消"
    >
      <a-radio-group v-model="upper_hot_shelf_state">
        <a-radio :value="1">上架</a-radio>
        <a-radio :value="2">下架</a-radio>
      </a-radio-group>
    </a-modal>

  </div>
</template>

<script>
import MyPagination from '../../components/Autism/myPagination'
import { queryGoodsPage, getGoodsList, goodsStatus, deleteGoods, uploadGoodsRecommendImg, saveRecommendImg, recommendStatus } from '@/api/goods'
import { queryCategory } from '@/api/goodsCategory'

const columns = [
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name'
  }, {
    title: '价格',
    dataIndex: 'price',
    key: 'price'
  }, {
    title: '库存',
    dataIndex: 'stock',
    key: 'stock'
  }, {
    title: '爆款推广状态',
    dataIndex: 'recommend_state',
    key: 'recommend_state',
    slots: { title: 'hot' },
    scopedSlots: { customRender: 'hot' }
  }, {
    title: '爆款推广顺序',
    dataIndex: 'recommend_serial_no',
    key: 'recommend_serial_no'
  }, {
    title: '上架状态',
    key: 'upper_shelf_state',
    dataIndex: 'upper_shelf_state',
    slots: { title: 'state' },
    scopedSlots: { customRender: 'state' }
  }, {
    title: '创建时间',
    key: 'create_date_time',
    dataIndex: 'create_date_time'
  }, {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' }
  }]

export default {
  name: 'GoodsList',
  components: {
    MyPagination

  },
  data () {
    return {
      upper_hot_shelf_state: 1,
      shelfHotVisible: false,
      imgUrl: '',
      uploading: false,
      fileList: [],
      shelfVisible: false,
      upper_shelf_state: 0,
      id: '',
      imgLoading: false,
      imageUrl: '',
      dialogModel: this.$form.createForm(this),
      visible: false,
      confirmLoading: false,
      categoryOptions: [],
      StatusOptions: [ { id: 0, name: '请选择状态' }, { id: 1, name: '上架' }, { id: 2, name: '下架' } ],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalCount: 0
      },
      currentTab: 0,
      queryParam: {
        name: '',
        category: '',
        upper_shelf_state: 1
      },
      columns,
      dataList: []
    }
  },
  beforeCreate () {
  },
  mounted () {
    this.getList()
    // 获取分类
    queryCategory({}).then((res) => {
      this.categoryOptions = res
    })
      .catch((err) => {
        console.log(err)
      })
  },
  methods: {
    delImg () {
      this.imgUrl = ''
    },
    // 编辑商品
    editGood (good) {
      this.$router.push({ path: 'edit-goods', query: { id: good.id } })
    },

    // 爆款上架操作
    changeHotState () {
      recommendStatus({
        id: this.id,
        recommend_state: this.upper_hot_shelf_state
      }).then((res) => {
        if (res) { this.$message.success('爆款上架操作成功！') }
        this.shelfHotVisible = false
        this.getList()
      })
        .catch((err) => {
          console.log(err)
          this.shelfHotVisible = false
          this.$message.error('爆款上架操作失败！')
        })
    },

    // 改变爆款上架状态
    changeHotShelves (status) {
      this.shelfHotVisible = true
      this.upper_shelf_state = status.upper_hot_shelf_state
      this.id = status.id
    },

    // 上传图片 取消
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
      this.imgUrl = ''
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },

    // 上传图片
    handleUpload: function () {
      const { fileList } = this
      const formData = new FormData()
      formData.append('file', fileList[0])
      this.uploading = true
      uploadGoodsRecommendImg(formData)
        .then((res) => {
          this.imgUrl = res[0].url
          this.uploading = false
          this.$message.success('上传成功！')
        })
        .catch((err) => {
          console.log(err)
          this.uploading = false
          this.$message.error('上传失败！')
        })
    },

    // 爆款编辑 弹窗
    editHotShelves (item) {
      console.log(item)
      this.visible = true
      this.id = item.id
      // 获取商品信息
      getGoodsList({ id: item.id })
        .then(res => {
          if (res.length > 0) {
            // 赋值
            this.dialogModel.setFieldsValue({
              'recommend_serial_no': res[0].recommend_serial_no,
              'slogan': res[0].slogan
            })
            this.imgUrl = res[0].recommend_img
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 根据 id 删除
    onDelete (id) {
      console.log(id)
      deleteGoods({
        id: id
      })
        .then((res) => {
          console.log(res)
          if (res) { this.$message.success('删除成功！') }
          if (res) {
            this.getList()
          }
        })
        .catch((err) => {
          console.log(err)
          this.$message.error('删除失败！')
        })
    },

    // 改变商品上架 状态
    changeState () {
      goodsStatus({
        id: this.id,
        upper_shelf_state: this.upper_shelf_state
      }).then((res) => {
        console.log(res)
        if (res) { this.$message.success('上架操作成功！') }
        this.shelfVisible = false
        this.getList()
      })
        .catch((err) => {
          console.log(err)
          this.shelfVisible = false
          this.$message.error('上架操作失败！')
        })
    },

    // 改变商品上架状态
    changeShelves (status) {
      this.shelfVisible = true
      this.upper_shelf_state = status.upper_shelf_state
      this.id = status.id
    },

    // 分页获取列表
    getList (isSearch) {
      let param = {
        page_index: this.pagination.pageNo,
        page_size: this.pagination.pageSize
      }

      if (isSearch) {
        param = Object.assign(this.pagination, this.queryParam)
      }
      queryGoodsPage(param)
        .then((res) => {
          console.log(res)
          this.dataList = res.collection
          console.log(this.dataList)
          this.pagination.pageNo = res.page_index
          this.pagination.pageSize = res.page_size
          this.pagination.totalCount = res.total_count
        })
        .catch((err) => {
          console.log(err)
        })
    },

    // 展示弹窗
    showModal () {
      this.visible = true
    },
    queryTable () {
      this.getList(true)
    },
    onChangePage (pageNo, pageSize) {
      this.pagination.pageNo = pageNo
      // 重新请求数据
      this.getList()
    },
    onShowSizeChangePage (pageNo, pageSize) {
      this.pagination.pageSize = pageSize
      // 重新请求数据
      this.getList()
    },
    statusChange (selectedItems) {
      this.queryParam.upper_shelf_state = selectedItems
    },

    // 保存爆款商品
    saveCategory () {
      this.confirmLoading = true
      this.dialogModel.validateFields((err, values) => {
        if (!err) {
          if (this.imgUrl === '') {
            this.$message.warning('请上传产品图片')
            return false
          }
          values.recommend_img = this.imgUrl
          values.id = this.id
          console.log(values)
          saveRecommendImg(values)
            .then((res) => {
              if (res) { this.$message.success('爆款商品编辑成功！') }
              console.log(res)
              this.visible = false
              this.confirmLoading = false
            })
            .catch((err) => {
              console.log(err)
              this.visible = false
              this.confirmLoading = false
              this.$message.error('爆款商品编辑失败！')
            })
        }
      })
    },
    handleCancel () {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
  .card {
    margin-bottom: 24px;
  }

  .popover-wrapper {
    /deep/ .antd-pro-pages-forms-style-errorPopover .ant-popover-inner-content {
      min-width: 256px;
      max-height: 290px;
      padding: 0;
      overflow: auto;
    }
  }

  .antd-pro-pages-forms-style-errorIcon {
    user-select: none;
    margin-right: 24px;
    color: #f5222d;
    cursor: pointer;

    i {
      margin-right: 4px;
    }
  }

  .antd-pro-pages-forms-style-errorListItem {
    padding: 8px 16px;
    list-style: none;
    border-bottom: 1px solid #e8e8e8;
    cursor: pointer;
    transition: all .3s;

    &:hover {
      background: #e6f7ff;
    }

    .antd-pro-pages-forms-style-errorIcon {
      float: left;
      margin-top: 4px;
      margin-right: 12px;
      padding-bottom: 22px;
      color: #f5222d;
    }

    .antd-pro-pages-forms-style-errorField {
      margin-top: 2px;
      color: rgba(0, 0, 0, .45);
      font-size: 12px;
    }
  }
</style>
